package org.nearby.note.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.nearby.note.bean.note;
import org.nearby.note.utils.DbUtil;


public class noteDaoImpl implements noteDao{
	private Connection conn;
	private PreparedStatement psmt;
	private ResultSet rs;
	private Statement smt;
	
	@Override
	public ArrayList<note> getAllNote(int user_id) {
		conn = DbUtil.getsqliteconnect(false);
		try {
			psmt = conn.prepareStatement("select * from note where user_id = ?");
			psmt.setInt(1, user_id);
			rs = psmt.executeQuery();
			
			ArrayList<note> notelist = new ArrayList<note>();
			while(rs.next()){
			    note n = new note();
				n.setNote_title(rs.getString("note_title"));
				n.setNote_content(rs.getString("note_content"));
				n.setUser_id(rs.getInt("user_id"));
				n.setLast_datetime(rs.getInt("last_datetime"));
				n.setNote_id(rs.getInt("note_id"));
				notelist.add(n);
			}
			return notelist;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close();
		}
		return null;
	}

	@Override
	public boolean delNote(int note_id) {
		return false;
	}

	@Override
	public int addNote(note n) {
	    return 0;
	}

	@Override
	public boolean updateNote(note n) {
	    conn = DbUtil.getsqliteconnect(false);
        long last_datetime = System.currentTimeMillis();
        
        try {
        	psmt = conn.prepareStatement("update note set note_title = ?, note_content = ?, last_datetime = ? where note_id = ?");
        	psmt.setString(1, n.getNote_title());
        	psmt.setString(2, n.getNote_content());
        	psmt.setString(3, Long.toString(last_datetime));
        	psmt.setInt(4, n.getNote_id());
        	int affected_rows = psmt.executeUpdate();
        	//System.out.println(psmt.toString());
            return affected_rows > 0;
            
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            close();
        }
        return false;
	}
	public void close() {
		try {
			if(smt != null){
				smt.close();
			}
			if (psmt != null) {
				psmt.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			Logger.getLogger(noteDaoImpl.class.getName()).log(Level.SEVERE, null, e);
		}
	}
	
}
